import axios, { AxiosInstance, AxiosResponse } from 'axios';
import { sm2,sm3 } from 'sm-crypto';
import md5 from 'js-md5';
import { Base64 } from 'js-base64'

const http: AxiosInstance = axios.create({
  baseURL: "/apiedu", // 从环境变量读取
  timeout: 60000,
});

function encrypt(params: string) {
  let encoded = Base64.encode(params)   //字符串转义,加密
  let md5Str = md5(md5(encoded) + "")         //和后台约定好的签名 '&TOKEN&'
  return { encoded, md5Str }
}

http.interceptors.request.use(
  config => {
    if (!config) {
      config = {};
    }
    if (!config.headers) {
      config.headers = {};
    }
    if (!config.headers['Content-Type']) {
      config.headers['Content-Type'] = 'application/json'
    }
    let rs = {
      md5Str: ''
    }
    let requrl: string = config.url ?? '';

    if (config.data) {
      if (!(config.data instanceof FormData)) {
        config.data = sm2.doEncrypt(JSON.stringify(config.data),
        "0488067646f26ca59747f541fa4e78e8c9af7210374d5a8da274df108d500633cf3dfe46af59077d4fbe604c5b5c6bbc084a095e09cf73f10df26994d9a48e87b7", 1);
      }
      config.headers['psm3'] = sm3(config.data)
      rs = encrypt(requrl + JSON.stringify(config.data))
      config.headers['signature'] = rs.md5Str
      // console.log('body====>>>>>', config.data)
    
    } else if (config.params) {
      rs = encrypt(requrl + JSON.stringify(config.params))
      config.headers['signature'] = rs.md5Str
    } else {
      rs = encrypt(requrl)
      config.headers['signature'] = rs.md5Str
    }
    return config
  }
);

export default http;